package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 系统集成
 */
@RestController
@RequestMapping("/system/SysIntegrate")
public class SysIntegrateController {
    @Autowired
    RestTemplateBuilder restTemplateBuilder;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ReUsingService reUsingService;
    @Autowired
    private ISysRoleDeptService roleDeptService;
    @Autowired
    private ISysRoleService roleService;

    /**
     * 集成企业微信通讯录
     */
    @PreAuthorize
    @ApiOperation("集成企业微信通讯录")
    @PostMapping("/integrateWxMailList")
    public com.ruoyi.common.core.web.domain.AjaxResult integrateWxMailList(@RequestBody IntegrateWxMailListVo vo) {
        RestTemplate restTemplate = restTemplateBuilder.build();
        //先获取企业微信Api的access_token
        String getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="
                + vo.getCorpId() + "&corpsecret=" + vo.getCorpSecret();
        ResponseEntity<GetWxTokenVo> wxTokenEntity = restTemplate.getForEntity(getTokenUrl, GetWxTokenVo.class);
        if (wxTokenEntity.getBody() != null && !wxTokenEntity.getBody().getErrcode().equals(0)) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("输入的corpid或corpsecret错误！");
        }
        String access_token = Objects.requireNonNull(wxTokenEntity.getBody()).getAccess_token();
        //获取到企业所有部门的列表
        String getAllDeptListUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + access_token;
        ResponseEntity<GetWxAllDeptVo> wxAllDeptEntity = restTemplate
                .getForEntity(getAllDeptListUrl, GetWxAllDeptVo.class);
        //向数据库添加企业微信通讯录的数据
        if (wxAllDeptEntity.getBody() != null && wxAllDeptEntity.getBody().getErrcode().equals(0)) {
            //新增的部门的默认部门类型
            String deptType = "1,2,3,4";
            String[] deptTypeArr = deptType.split(",");
            HashMap<Long, SysDept> map = new HashMap<>();
            HashSet<Long> deptIds = new HashSet<>();
            ArrayList<SysUser> sysUsers = new ArrayList<>();
            List<GetWxAllDeptVo.Department> wxDeptList = wxAllDeptEntity.getBody().getDepartment();
            List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.CORP_ID, vo.getCorpId()));
            if (deptList.size() > 0) {
                //集成企业微信时判断用户数据的集成情况
                ArrayList<String> dbUserNames = new ArrayList<>();
                ArrayList<String> wxUserNames = new ArrayList<>();
                HashMap<Long, Long> dbAndWxDeptIdMap = new HashMap<>();
                //获取数据库中企业微信用户名称集合
                HashSet<Long> dbDeptIds = new HashSet<>();
                deptList.forEach(item -> {
                    dbDeptIds.add(item.getDeptId());
                    dbAndWxDeptIdMap.put(item.getWxDeptId(), item.getDeptId());
                });
                List<SysUser> dbUserList = userService.list(new QueryWrapper<SysUser>().in(SysUser.DEPT_ID, dbDeptIds));
                dbUserList.forEach(item -> dbUserNames.add(item.getNickName()));
                //获取企业微信中的用户名称集合
                HashMap<String, GetWxDeptUsersVo.User> wxUserMap = new HashMap<>();
                HashMap<String, Long> userDeptMap = new HashMap<>();
                wxDeptList.forEach(item -> {
                    String getDeptUsersUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?" +
                            "access_token=" + access_token + "&department_id=" + item.getId();
                    ResponseEntity<GetWxDeptUsersVo> wxDeptUsers = restTemplate
                            .getForEntity(getDeptUsersUrl, GetWxDeptUsersVo.class);
                    if (wxDeptUsers.getBody() != null && wxDeptUsers.getBody().getErrcode().equals(0)) {
                        wxDeptUsers.getBody().getUserlist().forEach(item1 -> {
                            wxUserNames.add(item1.getName());
                            wxUserMap.put(item1.getName(), item1);
                            userDeptMap.put(item1.getName(), item.getId());
                        });
                    }
                });
                boolean a = reUsingService.compareListContent(dbUserNames, wxUserNames);

                //集成企业微信时判断部门数据的集成情况
                List<String> dbDeptNames = new ArrayList<>();
                List<String> wxDeptNames = new ArrayList<>();
                HashMap<String, GetWxAllDeptVo.Department> wxDeptMap = new HashMap<>();
                deptList.forEach(item -> dbDeptNames.add(item.getDeptShortName()));
                //用于后续查询
                wxDeptList.forEach(item -> {
                    wxDeptNames.add(item.getName());
                    wxDeptMap.put(item.getName(), item);
                });
                boolean b = reUsingService.compareListContent(dbDeptNames, wxDeptNames);

                if (a && b) { //微信的部门数据与本系统数据库中的一致
                    return com.ruoyi.common.core.web.domain.AjaxResult.error("你已经集成过企业微信了！");
                } else if (!b) { //微信的部门数据与本系统数据库中的不一致
                    if (dbDeptNames.size() > wxDeptNames.size()) {
                        //企业微信端删除了部门
                        HashSet<String> delDepts = new HashSet<>();
                        for (String dbDeptName : dbDeptNames) {
                            if (!wxDeptNames.contains(dbDeptName))
                                delDepts.add(dbDeptName);
                        }
                        List<SysDept> delDeptList = deptService.list(new QueryWrapper<SysDept>()
                                .in(SysDept.DEPT_SHORT_NAME, delDepts)
                                .eq(SysDept.CORP_ID, vo.getCorpId()));
                        HashSet<Long> delDeptIds = new HashSet<>();
                        delDeptList.forEach(item -> delDeptIds.add(item.getDeptId()));

                        CompletableFuture.runAsync(() -> deptService.removeByIds(delDeptIds));
                        CompletableFuture.runAsync(() -> roleService.remove(new QueryWrapper<SysRole>()
                                .in(SysRole.DEPT_ID, delDeptIds)));
                        CompletableFuture.runAsync(() -> roleDeptService.remove(new QueryWrapper<SysRoleDept>()
                                .in(SysRoleDept.DEPT_ID, delDeptIds)));

                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录成功！");
                    } else if (dbDeptNames.size() < wxDeptNames.size()) {
                        //企业微信端新增了部门
                        for (String wxDeptName : wxDeptNames) {
                            if (!dbDeptNames.contains(wxDeptName)) {
                                GetWxAllDeptVo.Department department = wxDeptMap.get(wxDeptName);
                                SysDept addDept = new SysDept();
                                SysDept parentDept = deptService.getOne(new QueryWrapper<SysDept>()
                                        .eq(SysDept.CORP_ID, vo.getCorpId())
                                        .eq(SysDept.WX_DEPT_ID, department.getParentid()), false);
                                addDept.setParentId(parentDept.getDeptId());
                                addDept.setAncestors(parentDept.getAncestors() + "," + parentDept.getDeptId());
                                addDept.setDeptFullName(parentDept.getDeptFullName() + department.getName());
                                addDept.setDeptShortName(department.getName());
                                addDept.setDeptType(deptType);
                                addDept.setWxDeptId(department.getId());
                                addDept.setCorpId(vo.getCorpId());
                                addDept.setCreateBy(SecurityUtils.getUsername());
                                addDept.setCreateTime(System.currentTimeMillis());
                                deptService.save(addDept);
                                deptIds.add(addDept.getDeptId());
                            }
                        }
                        CompletableFuture.runAsync(() -> {
                            if (deptIds.size() > 0) {
                                for (Long deptId : deptIds)
                                    deptService.addRoleInfo(deptTypeArr, deptId);
                            }
                        });
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录成功！");
                    }
                } else { //微信的员工数据与本系统数据库中的不一致
                    if (dbUserNames.size() > wxUserNames.size()) {
                        //企业微信端删除了员工
                        HashSet<String> delUsers = new HashSet<>();
                        dbUserNames.forEach(item -> {
                            if (!wxUserNames.contains(item))
                                delUsers.add(item);
                        });
                        userService.remove(new QueryWrapper<SysUser>().in(SysUser.NICK_NAME, delUsers)
                                .eq(SysUser.CORP_ID, vo.getCorpId()));
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录成功！");
                    } else if (dbUserNames.size() < wxUserNames.size()) {
                        //企业微信端添加了员工
                        ArrayList<SysUser> addUsers = new ArrayList<>();
                        wxUserNames.forEach(item -> {
                            if (!dbUserNames.contains(item)) {
                                SysUser user = new SysUser();
                                GetWxDeptUsersVo.User user1 = wxUserMap.get(item);
                                String userName = reUsingService.userNameIsExist(user1.getUserid())
                                        ? null : user1.getUserid();
                                String password = reUsingService.userNameIsExist(user1.getUserid())
                                        ? null : SecurityUtils.encryptPassword(user1.getUserid());
                                String phoneNumber = reUsingService.phoneNumberIsExist(user1.getMobile())
                                        ? null : user1.getMobile();
                                Long wxDeptId = userDeptMap.get(item);
                                Long dbDeptId = dbAndWxDeptIdMap.get(wxDeptId);
                                user.setDeptId(dbDeptId);
                                user.setUserName(userName);
                                user.setPassword(password);
                                user.setPhonenumber(phoneNumber);
                                user.setEmail(user1.getEmail());
                                user.setAvatar(user1.getAvatar());
                                user.setRemark("通过企业微信集成");
                                user.setNickName(user1.getName());
                                user.setWxNickName(user1.getUserid());
                                user.setCorpId(vo.getCorpId());
                                addUsers.add(user);
                            }
                        });
                        userService.saveBatch(addUsers);
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录成功！");
                    }
                }
            }
            //系统第一次集成企业微信的情况
            for (GetWxAllDeptVo.Department department : wxDeptList) {
                //逐条存储部门
                SysDept dept = new SysDept();
                if (department.getParentid().equals(0L)) {
                    dept.setParentId(0L);
                    dept.setAncestors("0");
                    dept.setDeptFullName(department.getName());
                } else {
                    SysDept parentDept = map.get(department.getParentid());
                    if (parentDept != null) {
                        dept.setParentId(parentDept.getDeptId());
                        dept.setAncestors(parentDept.getAncestors() + "," + parentDept.getDeptId());
                        dept.setDeptFullName(parentDept.getDeptFullName() + department.getName());
                    } else {
                        dept.setParentId(0L);
                    }
                }
                dept.setDeptType(deptType);
                dept.setWxDeptId(department.getId());
                dept.setDeptShortName(department.getName());
                dept.setCorpId(vo.getCorpId());
                dept.setCreateBy(SecurityUtils.getUsername());
                dept.setCreateTime(System.currentTimeMillis());
                deptService.save(dept);
                map.put(department.getId(), dept);
                deptIds.add(dept.getDeptId());
                //获取某部门的用户
                String getDeptUsersUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?" +
                        "access_token=" + access_token + "&department_id=" + department.getId();
                ResponseEntity<GetWxDeptUsersVo> wxDeptUsers = restTemplate
                        .getForEntity(getDeptUsersUrl, GetWxDeptUsersVo.class);
                //批量添加某部门的用户
                if (wxDeptUsers.getBody() != null && wxDeptUsers.getBody().getErrcode().equals(0)) {
                    for (GetWxDeptUsersVo.User user : wxDeptUsers.getBody().getUserlist()) {
                        SysUser sysUser = new SysUser();
                        String userName = reUsingService.userNameIsExist(user.getUserid())
                                ? null : user.getUserid();
                        String password = reUsingService.userNameIsExist(user.getUserid())
                                ? null : SecurityUtils.encryptPassword(user.getUserid());
                        String phoneNumber = reUsingService.phoneNumberIsExist(user.getMobile())
                                ? null : user.getMobile();
                        sysUser.setDeptId(dept.getDeptId());
                        sysUser.setUserName(userName);
                        sysUser.setPassword(password);
                        sysUser.setWxNickName(user.getUserid());
                        sysUser.setNickName(user.getName());
                        sysUser.setPhonenumber(phoneNumber);
                        sysUser.setEmail(user.getEmail());
                        sysUser.setAvatar(user.getAvatar());
                        sysUser.setRemark("通过企业微信集成");
                        sysUser.setCorpId(vo.getCorpId());
                        sysUsers.add(sysUser);
                    }
                }
            }
            CompletableFuture.runAsync(() -> userService.saveBatch(sysUsers));
            CompletableFuture.runAsync(() -> {
                if (deptIds.size() != 0) {
                    for (Long deptId : deptIds)
                        deptService.addRoleInfo(deptTypeArr, deptId);
                }
            });
            return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录成功！");
        }
        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成企业微信通讯录失败:" + Objects.requireNonNull(wxAllDeptEntity.getBody()).getErrmsg());
    }

    /**
     * 集成钉钉通讯录
     */
    @PreAuthorize
    @ApiOperation("集成钉钉通讯录")
    @PostMapping("/integrateDingMailList")
    public com.ruoyi.common.core.web.domain.AjaxResult integrateDingMailList(@RequestBody IntegrateDingMailListVo vo) {
        RestTemplate restTemplate = restTemplateBuilder.build();
        //先获取集成钉钉通讯录的AccessToken
        String getTokenUrl = "https://oapi.dingtalk.com/gettoken?appkey=" + vo.getAppKey() +
                "&appsecret=" + vo.getAppSecret();
        ResponseEntity<GetDingTokenVo> tokenEntity = restTemplate.getForEntity(getTokenUrl, GetDingTokenVo.class);
        if (tokenEntity.getBody() != null && !tokenEntity.getBody().getErrcode().equals(0)) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("输入的AppKey或者AppSecret错误！");
        }
        String access_token = Objects.requireNonNull(tokenEntity.getBody()).getAccess_token();

        //获取钉钉中的部门列表
        List<GetDingAllDeptVo.DingDept> dingDeptList = new ArrayList<>();
        //先获取根部门
        String getTopDeptUrl = "https://oapi.dingtalk.com/topapi/v2/department/get?access_token=" + access_token;
        GetDingUserJSONVo jsonVo1 = new GetDingUserJSONVo();
        jsonVo1.setDept_id(1L);
        ResponseEntity<GetDingTopDeptVo> dingTopDept = restTemplate
                .postForEntity(getTopDeptUrl, jsonVo1, GetDingTopDeptVo.class);
        if (Objects.requireNonNull(dingTopDept.getBody()).getErrcode().equals(0)) {
            GetDingAllDeptVo.DingDept dingDept = new GetDingAllDeptVo.DingDept();
            BeanUtils.copyProperties(dingTopDept.getBody().getResult(), dingDept);
            dingDept.setParent_id(0L);
            dingDeptList.add(dingDept);
        }
        //然后逐级获取根部门下的所有部门
        String getDingDeptListUrl = "https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token="
                + access_token;
        ResponseEntity<GetDingAllDeptVo> dingDeptListEntity = restTemplate
                .postForEntity(getDingDeptListUrl, jsonVo1, GetDingAllDeptVo.class);
        List<GetDingAllDeptVo.DingDept> resultList = Objects.requireNonNull(dingDeptListEntity.getBody()).getResult();
        dingDeptList.addAll(resultList);
        /*List<GetDingAllDeptVo.DingDept> dingDepts = reUsingService.recursionGetDingDept(resultList, access_token);
        if (dingDepts.size() > 0)
            dingDeptList.addAll(dingDepts);*/

        if (dingDeptListEntity.getBody() != null && dingDeptListEntity.getBody().getErrcode().equals(0)) {
            HashMap<Long, SysDept> map = new HashMap<>();
            HashSet<Long> deptIds = new HashSet<>();
            ArrayList<SysUser> users = new ArrayList<>();
            //新增的部门的默认部门类型
            String deptType = "1,2,3,4";
            String[] deptTypeArr = deptType.split(",");
            List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.APP_KEY, vo.getAppKey()));
            if (deptList.size() > 0) {
                //集成钉钉时判断用户数据的集成情况
                ArrayList<String> dbUserNames = new ArrayList<>();
                ArrayList<String> dingUserNames = new ArrayList<>();
                HashMap<Long, Long> dbAndDingDeptIdMap = new HashMap<>();
                //获取数据库中钉钉用户名称集合
                HashSet<Long> dbDeptIds = new HashSet<>();
                deptList.forEach(item -> {
                    dbDeptIds.add(item.getDeptId());
                    dbAndDingDeptIdMap.put(item.getDingDeptId(), item.getDeptId());
                });
                List<SysUser> dbUserList = userService.list(new QueryWrapper<SysUser>().in(SysUser.DEPT_ID, dbDeptIds));
                dbUserList.forEach(item -> dbUserNames.add(item.getNickName()));
                //获取钉钉中的用户名称集合
                HashMap<String, GetDingUserVo.Result.DingUser> dingUserMap = new HashMap<>();
                HashMap<String, Long> userDeptMap = new HashMap<>();
                dingDeptList.forEach(item -> {
                    String getDingUserUrl = "https://oapi.dingtalk.com/topapi/v2/user/list?access_token=" + access_token;
                    GetDingUserJSONVo jsonVo = new GetDingUserJSONVo();
                    jsonVo.setDept_id(item.getDept_id());
                    jsonVo.setCursor(0);
                    jsonVo.setSize(100);
                    ResponseEntity<GetDingUserVo> dingUserEntity = restTemplate
                            .postForEntity(getDingUserUrl, jsonVo, GetDingUserVo.class);
                    if (dingUserEntity.getBody() != null && dingUserEntity.getBody().getErrcode().equals(0)) {
                        dingUserEntity.getBody().getResult().getList().forEach(item1 -> {
                            dingUserNames.add(item1.getName());
                            dingUserMap.put(item1.getName(), item1);
                            userDeptMap.put(item1.getName(), item.getDept_id());
                        });
                    }
                });
                boolean a = reUsingService.compareListContent(dbUserNames, dingUserNames);

                //集成钉钉时判断部门数据的集成情况
                List<String> dbDeptNames = new ArrayList<>();
                List<String> dingDeptNames = new ArrayList<>();
                HashMap<String, GetDingAllDeptVo.DingDept> wxDeptMap = new HashMap<>();
                deptList.forEach(item -> dbDeptNames.add(item.getDeptShortName()));
                //用于后续查询
                dingDeptList.forEach(item -> {
                    dingDeptNames.add(item.getName());
                    wxDeptMap.put(item.getName(), item);
                });
                boolean b = reUsingService.compareListContent(dbDeptNames, dingDeptNames);

                if (a && b) { //钉钉的部门数据与本系统数据库中的一致
                    return com.ruoyi.common.core.web.domain.AjaxResult.error("你已经集成过钉钉了！");
                } else if (!b) { //钉钉的部门数据与本系统数据库中的不一致
                    if (dbDeptNames.size() > dingDeptNames.size()) {
                        //钉钉端删除了部门
                        HashSet<String> delDepts = new HashSet<>();
                        for (String dbDeptName : dbDeptNames) {
                            if (!dingDeptNames.contains(dbDeptName))
                                delDepts.add(dbDeptName);
                        }
                        List<SysDept> delDeptList = deptService.list(new QueryWrapper<SysDept>()
                                .in(SysDept.DEPT_SHORT_NAME, delDepts)
                                .eq(SysDept.APP_KEY, vo.getAppKey()));
                        HashSet<Long> delDeptIds = new HashSet<>();
                        delDeptList.forEach(item -> delDeptIds.add(item.getDeptId()));

                        CompletableFuture.runAsync(() -> deptService.removeByIds(delDeptIds));
                        CompletableFuture.runAsync(() -> roleService.remove(new QueryWrapper<SysRole>()
                                .in(SysRole.DEPT_ID, delDeptIds)));
                        CompletableFuture.runAsync(() -> roleDeptService.remove(new QueryWrapper<SysRoleDept>()
                                .in(SysRoleDept.DEPT_ID, delDeptIds)));

                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录成功！");
                    } else if (dbDeptNames.size() < dingDeptNames.size()) {
                        //钉钉端新增了部门
                        for (String dingDeptName : dingDeptNames) {
                            if (!dbDeptNames.contains(dingDeptName)) {
                                GetDingAllDeptVo.DingDept department = wxDeptMap.get(dingDeptName);
                                SysDept addDept = new SysDept();
                                SysDept parentDept = deptService.getOne(new QueryWrapper<SysDept>()
                                        .eq(SysDept.APP_KEY, vo.getAppKey())
                                        .eq(SysDept.DING_DEPT_ID, department.getParent_id()), false);
                                addDept.setParentId(parentDept.getDeptId());
                                addDept.setAncestors(parentDept.getAncestors() + "," + parentDept.getDeptId());
                                addDept.setDeptFullName(parentDept.getDeptFullName() + department.getName());
                                addDept.setDeptShortName(department.getName());
                                addDept.setDeptType(deptType);
                                addDept.setDingDeptId(department.getDept_id());
                                addDept.setAppKey(vo.getAppKey());
                                addDept.setCreateBy(SecurityUtils.getUsername());
                                addDept.setCreateTime(System.currentTimeMillis());
                                deptService.save(addDept);
                                deptIds.add(addDept.getDeptId());
                            }
                        }
                        CompletableFuture.runAsync(() -> {
                            if (deptIds.size() > 0) {
                                for (Long deptId : deptIds)
                                    deptService.addRoleInfo(deptTypeArr, deptId);
                            }
                        });
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录成功！");
                    }
                } else { //钉钉的员工数据与本系统数据库中的不一致
                    if (dbUserNames.size() > dingUserNames.size()) {
                        //钉钉端删除了员工
                        HashSet<String> delUsers = new HashSet<>();
                        dbUserNames.forEach(item -> {
                            if (!dingUserNames.contains(item))
                                delUsers.add(item);
                        });
                        userService.remove(new QueryWrapper<SysUser>().in(SysUser.NICK_NAME, delUsers)
                                .eq(SysUser.APP_KEY, vo.getAppKey()));
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录成功！");
                    } else if (dbUserNames.size() < dingUserNames.size()) {
                        //钉钉端添加了员工
                        ArrayList<SysUser> addUsers = new ArrayList<>();
                        dingUserNames.forEach(item -> {
                            if (!dbUserNames.contains(item)) {
                                SysUser user = new SysUser();
                                GetDingUserVo.Result.DingUser user1 = dingUserMap.get(item);
                                String userName = reUsingService.userNameIsExist(user1.getUserid())
                                        ? null : user1.getUserid();
                                String password = reUsingService.userNameIsExist(user1.getUserid())
                                        ? null : SecurityUtils.encryptPassword(user1.getUserid());
                                String phoneNumber = reUsingService.phoneNumberIsExist(user1.getMobile())
                                        ? null : user1.getMobile();
                                Long wxDeptId = userDeptMap.get(item);
                                Long dbDeptId = dbAndDingDeptIdMap.get(wxDeptId);
                                user.setDeptId(dbDeptId);
                                user.setUserName(userName);
                                user.setPassword(password);
                                user.setPhonenumber(phoneNumber);
                                user.setEmail(user1.getEmail());
                                user.setAvatar(user1.getAvatar());
                                user.setRemark("通过钉钉集成");
                                user.setNickName(user1.getName());
                                user.setAppKey(vo.getAppKey());
                                addUsers.add(user);
                            }
                        });
                        userService.saveBatch(addUsers);
                        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录成功！");
                    }
                }
            }
            //第一次集成钉钉时
            for (GetDingAllDeptVo.DingDept dingDept : dingDeptList) {
                //逐条添加部门
                SysDept dept = new SysDept();
                if (dingDept.getParent_id().equals(0L)) {
                    dept.setParentId(0L);
                    dept.setAncestors("0");
                    dept.setDeptFullName(dingDept.getName());
                } else {
                    SysDept parentDept = map.get(dingDept.getParent_id());
                    if (parentDept != null) {
                        dept.setParentId(parentDept.getDeptId());
                        dept.setAncestors(parentDept.getAncestors() + ","  + parentDept.getDeptId());
                        dept.setDeptFullName(parentDept.getDeptFullName() + dingDept.getName());
                    } else {
                        dept.setParentId(0L);
                    }
                }
                dept.setDeptType(deptType);
                dept.setDingDeptId(dingDept.getDept_id());
                dept.setDeptShortName(dingDept.getName());
                dept.setAppKey(vo.getAppKey());
                dept.setDingDeptId(dingDept.getDept_id());
                dept.setCreateBy(SecurityUtils.getUsername());
                dept.setCreateTime(System.currentTimeMillis());
                deptService.save(dept);
                map.put(dingDept.getDept_id(), dept);
                deptIds.add(dept.getDeptId());

                //获取某部门的用户列表
                String getDingUserUrl = "https://oapi.dingtalk.com/topapi/v2/user/list?access_token=" + access_token;
                GetDingUserJSONVo jsonVo = new GetDingUserJSONVo();
                jsonVo.setDept_id(dingDept.getDept_id());
                jsonVo.setCursor(0);
                jsonVo.setSize(100);
                ResponseEntity<GetDingUserVo> dingUserEntity = restTemplate
                        .postForEntity(getDingUserUrl, jsonVo, GetDingUserVo.class);
                //批量添加用户数据
                if (dingUserEntity.getBody() != null && dingUserEntity.getBody().getErrcode().equals(0)) {
                    List<GetDingUserVo.Result.DingUser> dingUserList = dingUserEntity.getBody().getResult().getList();
                    for (GetDingUserVo.Result.DingUser dingUser : dingUserList) {
                        SysUser sysUser = new SysUser();
                        String userName = reUsingService.userNameIsExist(dingUser.getUserid())
                                ? null : dingUser.getUserid();
                        String password = reUsingService.userNameIsExist(dingUser.getUserid())
                                ? null : SecurityUtils.encryptPassword(dingUser.getUserid());
                        String phoneNumber = reUsingService.phoneNumberIsExist(dingUser.getMobile())
                                ? null : dingUser.getMobile();
                        sysUser.setUserName(userName);
                        sysUser.setPassword(password);
                        sysUser.setDeptId(dept.getDeptId());
                        sysUser.setNickName(dingUser.getName());
                        sysUser.setPhonenumber(phoneNumber);
                        sysUser.setEmail(dingUser.getEmail());
                        sysUser.setAvatar(dingUser.getAvatar());
                        sysUser.setRemark("通过钉钉集成");
                        sysUser.setAppKey(vo.getAppKey());
                        users.add(sysUser);
                    }
                }
            }
            CompletableFuture.runAsync(() -> userService.saveBatch(users));
            CompletableFuture.runAsync(() -> {
                if (deptIds.size() != 0) {
                    for (Long deptId : deptIds) {
                        deptService.addRoleInfo(deptTypeArr, deptId);
                    }
                }
            });
            return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录成功！");
        }
        return com.ruoyi.common.core.web.domain.AjaxResult.success("集成钉钉通讯录失败:" + Objects.requireNonNull(dingDeptListEntity.getBody()).getErrmsg());
    }
}
